package com.chushouya.manager.dao.repository;

import com.chushouya.manager.dao.entity.ArticleCategoryEntity;
import com.chushouya.manager.dao.mapper.ArticleCategoryEntityMapper;
import com.chushouya.manager.dto.admin.article.ArticleCategoryQuery;
import com.general.framework.core.lang.Numbers;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.schema.PageResult;
import com.general.framework.data.mybatis.BaseRepository;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * Article repository for database operations
 */
@Repository
public class ArticleCategoryRepository extends BaseRepository<ArticleCategoryEntityMapper, ArticleCategoryEntity,Long> {

    /**
     * 查询文章分页列表
     *
     * @param query 查询条件
     * @return 分页列表
     */
    public PageResult<ArticleCategoryEntity> selectPage(ArticleCategoryQuery query) {
        return selectPage(query, buildExample(query));
    }

    /**
     * 查询下级分类列表
     *
     * @param id 父id
     * @return 分类列表
     */
    public List<ArticleCategoryEntity> selectSubList(Long id) {
        Example example = buildExample();
        example.and().andEqualTo("parentId", id).andEqualTo("delFlag", Numbers.INTEGER_ZERO);;
        return selectByExample(example);
    }
    /**
     * 查询文章分页列表
     *
     * @param query 查询条件
     * @return 分页列表
     */
    public ArticleCategoryEntity selectOne(ArticleCategoryQuery query) {
        return selectFirstOneByExample(buildExample(query));
    }

    private Example buildExample(ArticleCategoryQuery query) {
        Example example = buildExample();
        Example.Criteria c = example.and();
        c.andEqualTo("delFlag", Numbers.INTEGER_ZERO);
        if (query.getCategoryId() != null) {
            c.andEqualTo("categoryId", query.getCategoryId());
        }
        if (Strings.isNotBlank(query.getCategoryName())) {
            c.andLike("categoryName", Strings.format("%{}%", query.getCategoryName()));
        }
        example.orderBy("sort").orderBy("categoryId").desc();
        return example;
    }
}
